package com.sky.service.impl;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

/**
 * 分类业务层
 */
@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品
     */
    @Override
    @Transactional
    public void saveDishWithFlavor(DishDTO dishDTO) {

        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dishMapper.saveDish(dish);

        Long dishFlavorId = dish.getId();
        List<DishFlavor> flavors = dishDTO.getFlavors();

        flavors.forEach(flavor -> {
            flavor.setDishId(dishFlavorId);
        });

        dishFlavorMapper.insertBatch(flavors);

        Long categoryId = dishDTO.getCategoryId();
        String pattern = "dish_" + categoryId;
        cacheClean(pattern);

    }

    /**
     * 分页查询
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult dishPageQuery(DishPageQueryDTO dishPageQueryDTO) {

        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        String dishName = dishPageQueryDTO.getName();

        Page<DishVO> page = dishMapper.dishPageQuery(dishPageQueryDTO);


        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 批量删除
     * @param ids
     */
    @Override
    public void deleteDish(List<Long> ids) {
        //        起售中的菜品不能删除
        for (Long id : ids) {
            Dish dish = dishMapper.getDish(id);
            if (dish.getStatus() == StatusConstant.ENABLE){
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }

//        是否关联套餐，关联套餐的不能删除
        List<Long> setMeal = setmealDishMapper.isSetMeal(ids);
        if (setMeal!=null && setMeal.size()>0){
            throw new DeletionNotAllowedException(MessageConstant.CATEGORY_BE_RELATED_BY_DISH);
        }

//        批量删除菜品
        dishMapper.deleteByIds(ids);

//        删除关联口味
        dishFlavorMapper.deleteByIds(ids);

        String pattern = "dish_*";
        cacheClean(pattern);

    }

    @Override
    public DishVO getDish(Long id) {
        DishVO dishVO = new DishVO();
        Dish dish = dishMapper.getDish(id);
        BeanUtils.copyProperties(dish,dishVO);

        List<DishFlavor> dishFlavorList = dishFlavorMapper.getFlavors(id);

        dishVO.setFlavors(dishFlavorList);

        return dishVO;
    }

    /**
     * 修改菜品
     * @param dishDTO
     */
    @Override
    public void updateDishWithFlavors(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.updateDish(dish);

        //更新菜品口味，先删掉原来的口味，再插入更改后的口味
        List<DishFlavor> flavors = dishDTO.getFlavors();
        List<Long> ids = new ArrayList<>();
        ids.add(dish.getId());
        dishFlavorMapper.deleteByIds(ids);

        if (flavors!=null && flavors.size()>0){
            flavors.forEach(flavor->{
                flavor.setDishId(dishDTO.getId());
            });
            dishFlavorMapper.insertBatch(flavors);
        }

        String pattern = "dish_*";
        cacheClean(pattern);

    }

    @Override
    public void dishSaleStatus(Long id, Integer status) {
        dishMapper.dishSaleStatus(id,status);

    }

    @Override
    public List<Dish> list(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();

        List<Dish> dishList = dishMapper.list(dish);
        return dishList;
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getFlavors(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }

    private void cacheClean(String pattern){
        Collection keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }

}
